package com.work.yshop.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.work.yshop.R;
import com.work.yshop.adapter.CartAdapter;
import com.work.yshop.model.CartItem;
import com.work.yshop.model.Favorite;
import com.work.yshop.model.Order;
import com.work.yshop.model.Product;
import com.work.yshop.model.ProductHistory;
import com.work.yshop.mvp.contract.UserDataContract;
import com.work.yshop.mvp.presenter.UserDataPresenter;

import java.util.ArrayList;
import java.util.List;

/**
 * 购物车页面
 */
public class CartActivity extends AppCompatActivity implements UserDataContract.View, CartAdapter.OnCartItemClickListener {

    private Toolbar toolbar;
    private RecyclerView recyclerView;
    private View emptyView;
    private CheckBox cbSelectAll;
    private TextView tvTotalPrice;
    private Button btnCheckout;
    private View bottomLayout;
    
    private UserDataPresenter presenter;
    private CartAdapter adapter;
    private List<CartItem> cartItems = new ArrayList<>();
    
    // 直接购买相关
    private boolean isDirectBuy = false;
    private int directBuyProductId = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        
        // 获取Intent参数
        Intent intent = getIntent();
        if (intent != null) {
            isDirectBuy = intent.getBooleanExtra("direct_buy", false);
            directBuyProductId = intent.getIntExtra("product_id", -1);
        }
        
        // 初始化Presenter
        presenter = new UserDataPresenter(this);
        presenter.attachView(this);
        
        // 初始化视图
        initViews();
        setupToolbar();
        setupRecyclerView();
        
        // 设置监听器
        setupListeners();
        
        // 加载购物车数据
        presenter.loadCartItems();
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        recyclerView = findViewById(R.id.recycler_view);
        emptyView = findViewById(R.id.empty_view);
        cbSelectAll = findViewById(R.id.cb_select_all);
        tvTotalPrice = findViewById(R.id.tv_total_price);
        btnCheckout = findViewById(R.id.btn_checkout);
        bottomLayout = findViewById(R.id.layout_bottom);
    }
    
    private void setupToolbar() {
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("购物车");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }
    
    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new CartAdapter();
        adapter.setOnCartItemClickListener(this);
        recyclerView.setAdapter(adapter);
    }
    
    private void setupListeners() {
        // 全选/取消全选
        cbSelectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (buttonView.isPressed()) {
                for (CartItem item : cartItems) {
                    item.setSelected(isChecked);
                }
                adapter.notifyDataSetChanged();
                updateTotalPrice();
            }
        });
        
        // 结算
        btnCheckout.setOnClickListener(v -> {
            boolean hasSelected = false;
            List<CartItem> selectedItems = new ArrayList<>();
            
            for (CartItem item : cartItems) {
                if (item.isSelected()) {
                    hasSelected = true;
                    selectedItems.add(item);
                }
            }
            
            if (hasSelected) {
                // 只创建包含选定商品的订单
                presenter.createSelectedOrder(selectedItems, new UserDataContract.OrderCallback() {
                    @Override
                    public void onSuccess(Order order) {
                        Toast.makeText(CartActivity.this, "订单创建成功", Toast.LENGTH_SHORT).show();
                        // 跳转到订单详情页
                        Intent intent = new Intent(CartActivity.this, OrderListActivity.class);
                        intent.putExtra("tab_index", 2); // 待发货
                        startActivity(intent);
                    }

                    @Override
                    public void onError(String message) {
                        Toast.makeText(CartActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                Toast.makeText(this, "请选择要购买的商品", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    /**
     * 更新总价
     */
    private void updateTotalPrice() {
        double total = 0;
        boolean allSelected = true;
        
        for (CartItem item : cartItems) {
            if (item.isSelected()) {
                total += item.getSubtotal();
            } else {
                allSelected = false;
            }
        }
        
        cbSelectAll.setChecked(allSelected && !cartItems.isEmpty());
        tvTotalPrice.setText(String.format("¥%.2f", total));
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.detachView();
        }
    }

    // CartAdapter.OnCartItemClickListener 接口实现
    @Override
    public void onItemSelectChanged(int position, boolean isSelected) {
        cartItems.get(position).setSelected(isSelected);
        updateTotalPrice();
    }

    @Override
    public void onQuantityChanged(int position, int quantity) {
        CartItem item = cartItems.get(position);
        presenter.updateCartItemQuantity(item.getProductId(), quantity);
    }

    @Override
    public void onItemDeleted(int position) {
        CartItem item = cartItems.get(position);
        presenter.removeCartItem(item.getProductId());
    }

    // UserDataContract.View接口实现
    @Override
    public void showLoading() {
        emptyView.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
        bottomLayout.setVisibility(View.GONE);
    }

    @Override
    public void hideLoading() {
        emptyView.setVisibility(View.GONE);
    }

    @Override
    public void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showHistoryList(List<ProductHistory> historyList) {
        // 不需要实现
    }

    @Override
    public void showFavoriteList(List<Favorite> favoriteList) {
        // 不需要实现
    }

    @Override
    public void showCartItems(List<CartItem> cartItems) {
        this.cartItems = cartItems;
        
        if (cartItems.isEmpty()) {
            showEmptyView(2);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
            bottomLayout.setVisibility(View.VISIBLE);
            
            adapter.setData(cartItems);
            updateTotalPrice();
            
            // 处理直接购买场景
            if (isDirectBuy && directBuyProductId != -1) {
                handleDirectBuy();
            }
        }
    }

    @Override
    public void showOrderList(List<Order> orderList) {
        // 不需要实现
    }

    @Override
    public void showEmptyView(int type) {
        recyclerView.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
        bottomLayout.setVisibility(View.GONE);
    }

    @Override
    public void showResult(boolean success, String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        
        if (success) {
            // 如果是创建订单成功，刷新购物车
            presenter.loadCartItems();
        }
    }
    
    /**
     * 处理直接购买场景
     */
    private void handleDirectBuy() {
        // 打印日志，帮助调试
        Log.d("CartActivity", "处理直接购买: productId=" + directBuyProductId);
        Log.d("CartActivity", "购物车商品数量: " + cartItems.size());
        
        // 遍历所有购物车商品，输出详细信息
        for (int i = 0; i < cartItems.size(); i++) {
            CartItem item = cartItems.get(i);
            Product product = item.getProduct();
            String productName = product != null ? product.getName() : "未知";
            double productPrice = product != null ? product.getPrice() : 0;
            String imageUrl = product != null ? product.getImageUrl() : "";
            
            Log.d("CartActivity", "购物车商品[" + i + "]: " +
                "id=" + item.getProductId() + 
                ", name=" + productName + 
                ", price=" + productPrice + 
                ", quantity=" + item.getQuantity() + 
                ", imageUrl=" + (imageUrl.isEmpty() ? "空" : "有"));
        }
        
        // 标记该商品为选中状态
        boolean found = false;
        List<CartItem> selectedItems = new ArrayList<>();
        
        for (int i = 0; i < cartItems.size(); i++) {
            CartItem item = cartItems.get(i);
            
            // 使用字符串比较来确保类型匹配
            String itemIdStr = String.valueOf(item.getProductId());
            String targetIdStr = String.valueOf(directBuyProductId);
            
            if (itemIdStr.equals(targetIdStr)) {
                Log.d("CartActivity", "找到匹配商品: " + item.getProductId() + 
                      ", 使用字符串比较: " + itemIdStr + " equals " + targetIdStr);
                item.setSelected(true);
                selectedItems.add(item);
                found = true;
            } else {
                item.setSelected(false);
            }
        }
        
        if (found) {
            Log.d("CartActivity", "成功找到商品，准备结算");
            // 更新UI
            adapter.notifyDataSetChanged();
            updateTotalPrice();
            
            // 自动进入结算流程，只结算选中的商品
            presenter.createSelectedOrder(selectedItems, new UserDataContract.OrderCallback() {
                @Override
                public void onSuccess(Order order) {
                    Toast.makeText(CartActivity.this, "订单创建成功", Toast.LENGTH_SHORT).show();
                    // 跳转到订单详情页
                    Intent intent = new Intent(CartActivity.this, OrderListActivity.class);
                    intent.putExtra("tab_index", 2); // 待发货
                    startActivity(intent);
                    
                    // 重置直接购买标记，防止返回时再次触发
                    isDirectBuy = false;
                    directBuyProductId = -1;
                }

                @Override
                public void onError(String message) {
                    Toast.makeText(CartActivity.this, "创建订单失败: " + message, Toast.LENGTH_SHORT).show();
                    // 重置直接购买标记
                    isDirectBuy = false;
                    directBuyProductId = -1;
                }
            });
        } else {
            Log.e("CartActivity", "未找到匹配商品: " + directBuyProductId);
            Toast.makeText(this, "未找到商品ID: " + directBuyProductId, Toast.LENGTH_SHORT).show();
            // 重置直接购买标记
            isDirectBuy = false;
            directBuyProductId = -1;
        }
    }
} 